<template>
  <zy-list-page-layout>
    <!-- 搜索区域 -->
    <template #search>
      <zy-query-form :query-params="queryParams" @query="handleQuery" @reset="resetQuery">
        <el-form-item label="用户名" prop="userName">
          <el-input
            v-model="queryParams.userName"
            placeholder="请输入用户名"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="登录账号" prop="loginName">
          <el-input
            v-model="queryParams.loginName"
            placeholder="请输入登录账号"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input
            v-model="queryParams.phone"
            placeholder="请输入手机号码"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
      </zy-query-form>
    </template>

    <!-- 操作按钮区域 -->
    <template #action>
      <el-button type="primary" @click="handleAdd"> 新增用户 </el-button>
    </template>

    <!-- 表格区域 -->
    <template #table>
      <zy-pagination-table
        ref="paginationTableRef"
        :query="getUserList"
        :query-params="queryParams"
        :auto-load="false"
        v-model:data="userList"
        v-model:total="total"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column prop="userName" label="用户名" min-width="120" />
        <el-table-column prop="loginName" label="登录账号" min-width="120" />
        <el-table-column prop="phone" label="手机号码" min-width="120" />
        <el-table-column prop="email" label="电子邮箱" min-width="180" />
        <el-table-column prop="loginFailCount" label="登录失败次数" width="120" align="center" />
        <zy-table-dict-column
          prop="isLock"
          label="是否锁定"
          width="100"
          dict-type-code="YES_NO"
          :tag-type-map="{ true: 'danger', false: 'success' }"
          default-tag-type="success"
        />
        <el-table-column prop="loginTime" label="最后登录时间" min-width="160" align="center" />
        <el-table-column prop="createTime" label="创建时间" min-width="180" align="center" />
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)"> 编辑 </el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </zy-pagination-table>
    </template>
  </zy-list-page-layout>

  <!-- 用户表单对话框 -->
  <Detail
    v-model:visible="dialogVisible"
    :user-data="currentUser"
    :is-edit="isEdit"
    @success="handleSuccess"
  />
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox, ElInput, ElButton, ElTableColumn, ElFormItem } from 'element-plus'
import { getUserList, deleteUser, SysUser, UserQueryParams } from '@/api/system/user'
// Business 组件已全局注册，无需导入
import Detail from './Detail.vue'

// 响应式数据
const total = ref(0)
const userList = ref<SysUser[]>([])
const dialogVisible = ref(false)
const currentUser = ref<SysUser>()
const isEdit = ref(false)

const paginationTableRef = ref()

// 查询参数
const queryParams = reactive<UserQueryParams>({
  pageNum: 1,
  pageSize: 10,
  userName: '',
  loginName: '',
  phone: '',
  systemCode: ''
})

// 生命周期
onMounted(() => {
  nextTick(() => {
    if (paginationTableRef.value) {
      paginationTableRef.value.loadData()
    }
  })
})

// 搜索
const handleQuery = () => {
  queryParams.pageNum = 1
  if (paginationTableRef.value) {
    paginationTableRef.value.handleQuery()
  }
}

// 重置搜索
const resetQuery = () => {
  queryParams.userName = ''
  queryParams.loginName = ''
  queryParams.phone = ''
  queryParams.systemCode = ''
  queryParams.pageNum = 1
  if (paginationTableRef.value) {
    paginationTableRef.value.resetQuery()
  }
}

// 新增用户
const handleAdd = () => {
  isEdit.value = false
  currentUser.value = undefined
  dialogVisible.value = true
}

// 编辑用户
const handleEdit = (row: SysUser) => {
  isEdit.value = true
  currentUser.value = { ...row }
  dialogVisible.value = true
}

// 删除用户
const handleDelete = async (row: SysUser) => {
  try {
    await ElMessageBox.confirm('确认删除该用户吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    if (!row.userId) {
      ElMessage.error('用户ID不能为空')
      return
    }

    const result: any = await deleteUser(row.userId)
    if (result === true || result.data === true) {
      ElMessage.success('删除成功')
      if (paginationTableRef.value) {
        paginationTableRef.value.loadData()
      }
    } else {
      ElMessage.error('删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除用户失败:', error)
      ElMessage.error('删除用户失败')
    }
  }
}

// 表单提交成功回调
const handleSuccess = () => {
  if (paginationTableRef.value) {
    paginationTableRef.value.loadData()
  }
}
</script>
